/**********************************************
 * Author: Nikhil Kishore
 * Date: July 18, 2014
 * Description: Random test generator for
 * adventurer card.
**********************************************/



#include "dominion.h"
#include "dominion_helpers.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "rngs.h"
#include "math.h"
#include <time.h>

int testAdventurer(int currentPlayer, struct gameState *post, int randomSeed) {
	int z = 0; // this is the counter for the temp hand
	int drawntreasure = 0;
	int cardDrawn;
	int temphand[MAX_HAND];
	struct gameState pre;
	int handPos = 0;
	int counter = 0;
	int result;

	memcpy(&pre, post, sizeof(struct gameState));

	SelectStream(2);
	PutSeed(randomSeed);

	result = cardEffect(adventurer, 0, 0, 0, post, 0, 0);
	PutSeed(randomSeed);

	while(drawntreasure < 2) {
   	   if (pre.deckCount[currentPlayer] < 1){//if the deck is empty we need to shuffle discard and add to deck
	      shuffle(currentPlayer, &pre);
   	   }

	   if (drawCard(currentPlayer, &pre) == 0) {
	      counter++;
	   }

	   cardDrawn = pre.hand[currentPlayer][pre.handCount[currentPlayer] - 1];//top card of hand is most recently drawn card.
  
	   if (cardDrawn == copper || cardDrawn == silver || cardDrawn == gold)
	      drawntreasure++;
	   else {
	      temphand[z]=cardDrawn;
	      pre.handCount[currentPlayer]--; //this should just remove the top card (the most recently drawn one).
	      counter--;
	      z++;
	   }
	}

	while(z-1 >= 0) {
	   pre.discard[currentPlayer][pre.discardCount[currentPlayer]++]=temphand[z-1]; // discard all cards in play that have been drawn
   	   z=z-1;
	}

	discardCard(handPos, currentPlayer, &pre, 0);

	assert(result == 0);
	//assert(post->handCount[currentPlayer] == saveHandCount + counter); // causing seg fault 

	return 0;
}

int main() {
	int n, i, p;
	struct gameState Game;
	srand(time(NULL));
	int randomSeed = rand();

	printf ("Testing Adventurer card\n");
	printf ("RANDOM TESTS\n");

	SelectStream(3);
	PutSeed(randomSeed);

	for (n = 0; n < 2000; n++) {
	   SelectStream(3);
   	   for (i = 0; i < sizeof(struct gameState); i++) {
	      ((char*)&Game)[i] = floor(Random() * 256);
	   }

	   p = floor(Random() * MAX_PLAYERS);
   	   Game.whoseTurn = p;
	   Game.deckCount[p] = floor(Random() * MAX_DECK);
	   Game.discardCount[p] = floor(Random() * MAX_DECK);
	   Game.handCount[p] = floor(Random() * MAX_HAND);
	   Game.playedCardCount = floor(Random() * MAX_DECK);

	   for (i = 0; i < Game.handCount[p]; i++) {
	      Game.hand[p][i] = floor(Random() * (treasure_map + 1));
	   }

	   for (i = 0; i < Game.discardCount[p]; i++) {
	      Game.discard[p][i] = floor(Random() * (treasure_map + 1));
	   }

	   for (i = 0; i < Game.deckCount[p]; i++) {
	      Game.deck[p][i] = floor(Random() * (treasure_map + 1));
	   }

	   testAdventurer(p, &Game, randomSeed);
	}

	printf("ALL TESTS OK\n\n");
	return 0;
}
